package io.bhex.app.trade.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.trade.presenter.CalculatorOfProfitPresenter;
import io.bhex.app.utils.AnimalUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.FuturensBaseToken;
import io.bhex.sdk.trade.bean.CalculateProfitResponse;

/**
 * ================================================
 * 作   者：ppzhao
 * 创建时间：2020-02-21
 * 邮   箱：
 * 描   述：收益率计算器
 * ================================================
 */

public class CalculatorOfProfitFragment extends BaseFragment<CalculatorOfProfitPresenter, CalculatorOfProfitPresenter.CalculatorOfProfitUI> implements CalculatorOfProfitPresenter.CalculatorOfProfitUI, View.OnClickListener {
    private boolean isLong;
    private View tab;
    private View buyTabRela;
    private View sellTabRela;
    private View buySellTabBg;
    private TextView buyTabTx;
    private TextView sellTabTx;
    private List<CoinPairBean> selectSymbolList = new ArrayList<CoinPairBean>();
    private List<String> selectSymbolNameList = new ArrayList<String>();
    private TextView contractName;
    private String quantityUnit;
    private String displayTokenId;
    private EditText leverEt;
    private EditText openPriceEt;
    private EditText openQuantityEt;
    private EditText closePriceEt;
    private EditText closeQuantityEt;
    private CoinPairBean currentCoinPair;

    @Override
    protected CalculatorOfProfitPresenter.CalculatorOfProfitUI getUI() {
        return this;
    }

    @Override
    protected CalculatorOfProfitPresenter createPresenter() {
        return new CalculatorOfProfitPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_calculator_profit_layout,null,false);


    }

    @Override
    protected void initViews() {
        super.initViews();

        setShadow(R.id.select_contract_rela);
        setShadow(R.id.tab);
        setShadow(R.id.rela_lever);
        setShadow(R.id.rela_open_price);
        setShadow(R.id.rela_open_quantity);
        setShadow(R.id.rela_close_price);
        setShadow(R.id.rela_close_quantity);
        setShadow(R.id.rela_result);

        tab = viewFinder.find(R.id.tab);
        buyTabRela = viewFinder.find(R.id.tab_bid_rela);
        sellTabRela = viewFinder.find(R.id.tab_ask_rela);
        buySellTabBg = viewFinder.find(R.id.tab_bg);
        buyTabTx = viewFinder.find(R.id.tab_bid);
        sellTabTx = viewFinder.find(R.id.tab_ask);
        contractName = viewFinder.find(R.id.contract_name);

        switchBuySellTab(true); //默认多仓

        leverEt = viewFinder.editText(R.id.lever);
        openPriceEt = viewFinder.editText(R.id.openPrice);
        openQuantityEt = viewFinder.editText(R.id.openQuantity);
        closePriceEt = viewFinder.editText(R.id.closePrice);
        closeQuantityEt = viewFinder.editText(R.id.closeQuantity);

        quantityUnit = getString(R.string.string_futures_unit);

        initContractSymbols();
        setDefaultSelectSymbol();
    }

    private void initContractSymbols() {
        selectSymbolList.clear();
        selectSymbolNameList.clear();
        HashMap<String, CoinPairBean> contractSymbolMap = SymbolDataManager.GetInstance().getContractSymbolMap();
        if (contractSymbolMap != null) {
            for (String key : contractSymbolMap.keySet()) {
                CoinPairBean coinPairBean = contractSymbolMap.get(key);
                selectSymbolList.add(coinPairBean);
                selectSymbolNameList.add(coinPairBean.getSymbolName());
            }
        }
    }

    private void setDefaultSelectSymbol() {
        if (selectSymbolList != null && selectSymbolList.size()>0) {
            CoinPairBean coinPairBean = selectSymbolList.get(0);
            setSelectContract(coinPairBean);
        }
    }

    private void setSelectContract(CoinPairBean coinPairBean) {
        if (coinPairBean != null) {
            if (currentCoinPair != null) {
                if (!currentCoinPair.getSymbolId().equals(coinPairBean.getSymbolId())) {
                    clearViewData();
                }
            }
            currentCoinPair = coinPairBean;
            String quoteTokenName = coinPairBean.getQuoteTokenName();
            FuturensBaseToken baseTokenFutures = coinPairBean.baseTokenFutures;
            if (baseTokenFutures != null) {
                displayTokenId = baseTokenFutures.getDisplayTokenId();

            }
            contractName.setText(coinPairBean.getSymbolName());
            viewFinder.textView(R.id.openPriceUnit).setText(displayTokenId);
            viewFinder.textView(R.id.openQuantityUnit).setText(quantityUnit);
            viewFinder.textView(R.id.closePriceUnit).setText(displayTokenId);
            viewFinder.textView(R.id.closeQuantityUnit).setText(quantityUnit);

            viewFinder.textView(R.id.openMarginUnit).setText(quoteTokenName);
            viewFinder.textView(R.id.openTakerFeeUnit).setText(quoteTokenName);
            viewFinder.textView(R.id.openMakerFeeUnit).setText(quoteTokenName);
            viewFinder.textView(R.id.closeTakerFeeUnit).setText(quoteTokenName);
            viewFinder.textView(R.id.closeMakerFeeUnit).setText(quoteTokenName);
            viewFinder.textView(R.id.profitUnit).setText(quoteTokenName);
            viewFinder.textView(R.id.profitRateUnit).setText("%");

        }
    }

    private void clearViewData() {
        leverEt.setText("");
        openPriceEt.setText("");
        openQuantityEt.setText("");
        closePriceEt.setText("");
        closeQuantityEt.setText("");

        viewFinder.textView(R.id.openMargin).setText(getString(R.string.string_placeholder));
        viewFinder.textView(R.id.openTakerFee).setText(getString(R.string.string_placeholder));
        viewFinder.textView(R.id.openMakerFee).setText(getString(R.string.string_placeholder));
        viewFinder.textView(R.id.closeTakerFee).setText(getString(R.string.string_placeholder));
        viewFinder.textView(R.id.closeMakerFee).setText(getString(R.string.string_placeholder));
        viewFinder.textView(R.id.profit).setText(getString(R.string.string_placeholder));
        viewFinder.textView(R.id.profitRate).setText(getString(R.string.string_placeholder));
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.select_contract_rela).setOnClickListener(this);
        viewFinder.find(R.id.tab_bid_rela).setOnClickListener(this);
        viewFinder.find(R.id.tab_ask_rela).setOnClickListener(this);
        viewFinder.find(R.id.btn_calculator).setOnClickListener(this);
    }


    private void setShadow(int viewId) {
        ShadowDrawable.setShadow(viewFinder.find(viewId));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.select_contract_rela:
                showSelectToken();
                break;
            case R.id.tab_bid_rela:
                switchBuySellTab(true);
                AnimalUtils.transAnimRun(buySellTabBg, buySellTabBg.getWidth(), 0);

                break;
            case R.id.tab_ask_rela:
                switchBuySellTab(false);
                AnimalUtils.transAnimRun(buySellTabBg, 0, buySellTabBg.getWidth());

                break;
            case R.id.btn_calculator:
                calculateProfit();
                break;
        }
    }

    /**
     * 计算收益
     */
    private void calculateProfit() {

        String lever = leverEt.getText().toString().trim();
        String openPrice = openPriceEt.getText().toString().trim();
        String openQuantity = openQuantityEt.getText().toString().trim();
        String closePrice = closePriceEt.getText().toString().trim();
        String closeQuantity = closeQuantityEt.getText().toString().trim();
        if (currentCoinPair == null) {
            return;
        }
        if (TextUtils.isEmpty(lever)) {
            ToastUtils.showShort(getString(R.string.string_input_lever));
            return;
        }
        if (TextUtils.isEmpty(openPrice)) {
            ToastUtils.showShort(getString(R.string.string_input_open_price));
            return;
        }
        if (TextUtils.isEmpty(openQuantity)) {
            ToastUtils.showShort(getString(R.string.string_input_open_quantity));
            return;
        }
        if (!TextUtils.isEmpty(closePrice)) {
            if (TextUtils.isEmpty(closeQuantity)) {
                ToastUtils.showShort(getString(R.string.string_input_close_quantity));
                return;
            }
            if (NumberUtils.sub(closeQuantity,openQuantity)>0) {
                ToastUtils.showShort(getString(R.string.string_not_allow_close_quantity_over_open_quantity));
                return;
            }
        }
        if (!TextUtils.isEmpty(closeQuantity)) {
            if (TextUtils.isEmpty(closePrice)) {
                ToastUtils.showShort(getString(R.string.string_input_close_price));
                return;
            }
            if (NumberUtils.sub(closeQuantity,openQuantity)>0) {
                ToastUtils.showShort(getString(R.string.string_not_allow_close_quantity_over_open_quantity));
                return;
            }
        }

        getPresenter().calculateProfit(isLong,currentCoinPair,lever,openPrice,openQuantity,closePrice,closeQuantity);
    }

    @Override
    public void showResult(CalculateProfitResponse response) {
        if (response != null) {
            viewFinder.textView(R.id.openMargin).setText(response.getOrderMargin());
            viewFinder.textView(R.id.openTakerFee).setText(response.getTakerOpenFee());
            viewFinder.textView(R.id.openMakerFee).setText(response.getMakerOpenFee());
            viewFinder.textView(R.id.closeTakerFee).setText(response.getTakerCloseFee());
            viewFinder.textView(R.id.closeMakerFee).setText(response.getMakerCloseFee());
            viewFinder.textView(R.id.profit).setText(response.getProfit());
            viewFinder.textView(R.id.profitRate).setText(response.getProfitRate());
        }

    }

    /**
     * 切换买卖tab
     *
     * @param isLongPosition
     */
    protected void switchBuySellTab(boolean isLongPosition) {
        isLong = isLongPosition;
        if (isLong) {
            buyTabTx.setTextColor(getResources().getColor(R.color.blue));
            sellTabTx.setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
            ShadowDrawable.setShadow(tab);
            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_blue);
        } else {
            buyTabTx.setTextColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
            sellTabTx.setTextColor(getResources().getColor(R.color.blue));
            ShadowDrawable.setShadow(tab);
            buySellTabBg.setBackgroundResource(R.drawable.bg_corner_rect_blue);
        }
    }

    /**
     * token选择
     */
    private void showSelectToken() {

        AlertView selectContractAlert = new AlertView(getString(R.string.string_select_token), null, getString(R.string.string_cancel), null, selectSymbolNameList.toArray(new String[selectSymbolNameList.size()]), getActivity(), AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    return;
                }
                if (position < selectSymbolNameList.size()) {
                    CoinPairBean selectContract = selectSymbolList.get(position);
                    setSelectContract(selectContract);
                }
            }
        });
        selectContractAlert.show();
    }
}
